package cn.simon.controller;

import cn.simon.model.Comment;
import cn.simon.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;
    @GetMapping("/addComment")
    public String addComment(){
        return "addComment";
    }
    @PostMapping("/addComment")
    public String addComment(Comment comment, Model model){
        Date date = new Date();
        comment.setCommentDate(date);
        model.addAttribute("comment",comment);
        commentService.addComment(comment);
        int goodsId = comment.getGoodsId();
        return "redirect:/comment/findByGoodsId/"+goodsId;
    }
    @GetMapping("/findByGoodsId/{id}")
    public String findByGoodsId(@PathVariable Integer id, Model model){
        List<Comment> list = commentService.findByGoodsId(id);
        model.addAttribute("list",list);
        return "comment";
    }

    @GetMapping("/deleteByCommentId")
    @Transactional(rollbackFor = Exception.class)
    public String deleteByCommentId(Integer id,Integer gid){
        commentService.deleteByCommentId(id);
        return "redirect:/comment/findByGoodsId/"+gid;
    }

    @PostMapping("/reply")
    public String reply(Comment comment, Model model) {
        Comment comment2 = Comment.builder()
                .goodsId(comment.getGoodsId())
                .commentedId(comment.getCommentId())
                .build();
        model.addAttribute("comment2",comment2);
        Comment comment1 = commentService.selectById(comment2.getCommentedId());
        //获得用户name
        int i = comment1.getUserId();
        String name = "ce测试";
        String context = "@" + name + " " + comment.getCommentContent();

        comment.setCommentContent(context);
        if (comment.getCommentedId() != 0) {
            comment.setCommentedId(comment1.getCommentId());
        }
        Date date = new Date();
        comment.setCommentDate(date);
        model.addAttribute("comment", comment);
        commentService.addComment(comment);
        int goodsId = comment.getGoodsId();
        return "redirect:/comment/findByGoodsId/" + goodsId;
    }
}



